package com.hoshiicloud.purchase.controller;

import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.purchase.Po;
import com.hoshiicloud.purchase.Podetail;
import com.hoshiicloud.purchase.Purchase;
import com.hoshiicloud.purchase.param.PodetailAddParam;
import com.hoshiicloud.purchase.service.PurchaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:campchen
 * @Date:Created in 下午 03:46 2019/5/31
 * @PACKAGENAME com.hoshiicloud.purchase.controller
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/purchase")
@Api(value = "备货单/采购单", tags = {"备货单/采购单"})
public class PurchaseController {

    @Autowired
    private PurchaseService purchaseService;


    /**
     * @param purchase（poAddParam,podetailParam）
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 实采单：采购单--销售订单自动生成  备货单--采购人员采购  新增
     */
    @PostMapping("/actualPurchase")
    @ApiOperation(value = "备货单/采购单")
    public Response actualPurchase(@RequestBody @Valid Purchase purchase) {
        Po po;
        List<Podetail> podetailList = new ArrayList<>();
        try {
            //将PoAddParam与Po进行匹配
            po = BeanUtils.covertType(purchase.getPoAddParam(), Po.class);
            //将list中每一个PodetailAddParam与Podetail进行匹配，最后在组装成podetailList
            for (PodetailAddParam podetailAddParam : purchase.getList()) {
                Podetail podetail = BeanUtils.covertType(podetailAddParam, Podetail.class);
                podetailList.add(podetail);
            }
        } catch (ServiceException e) {
            log.error("新增异常", e);
            return Response.failed(e.getError().getMsg());
        } catch (Exception e) {
            log.error("新增异常", e);
            return Response.failed(e.getMessage());
        }
        if (purchase.getPoAddParam().getType() == 9 || purchase.getPoAddParam().getType() == 1) {
            return Response.data(purchaseService.saveActualPurchase(po, podetailList));
        } else {
            throw new ServiceException(CommonError.error("新增失败,采购单类型有误"));
        }

    }
}
